package egovframework.npqs.pqi.mobile.activity.disinfection;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.jsoncontent.DisinfectionCommandItem;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.DisinfectionCommListItem;
import egovframework.npqs.pqi.mobile.jsonparser.DisinfectionCommandThread;
import egovframework.npqs.pqi.mobile.jsonparser.DisinfectionCommandThread.DisinfectionCommandThreadCallback;

//소독명령서
public class DisinfectionCommActivity extends Activity implements 
	DisinfectionCommandThreadCallback, OnClickListener{
	private TextView titleTxt;	// 상단 타이틀
	private AppStatus myapp;
	private Context context;
	private String serchRecNo;
	
	private TextView headerTotTxt, navigation;
	private TextView content_1_1, content_1_2, content_2_1, content_2_2;
	private TextView content_3_1, content_4_1, content_4_2, content_5_1;
	private TextView content_6_1, content_7_1, content_8_1, content_9_1, content_10_1;

	private ImageButton upBtn, downBtn, btnHome, btn_exit;
	
	private DisinfectionCommandThread disfectionThread;
	private DisinfectionCommandItem disfectionItem;
	private ArrayList<DisinfectionCommListItem>	disfectionListItem;
	
	private ListView listView;
	private DisinfectionCommAdapter disinfectionAdapter;
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	/* G-MOBILE 변수*/
    private String temp;
    
    private String mResult;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("소독명령서");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_disinf_comm);
		
		Intent intent = getIntent();
		serchRecNo = intent.getStringExtra("searchRecNo");
		
		
		init();
	}
	
	private void init(){
		context = this;
		//context = getApplicationContext();
		myapp = (AppStatus) getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("소독명령서");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		content_1_1 = (TextView)findViewById(R.id.content_1_1);
		content_1_2 = (TextView)findViewById(R.id.content_1_2);
		content_2_1 = (TextView)findViewById(R.id.content_2_1);
		content_2_2 = (TextView)findViewById(R.id.content_2_2);
		content_3_1 = (TextView)findViewById(R.id.content_3_1);
		content_4_1 = (TextView)findViewById(R.id.content_4_1);
		content_4_2 = (TextView)findViewById(R.id.content_4_2);
		content_5_1 = (TextView)findViewById(R.id.content_5_1);
		content_6_1 = (TextView)findViewById(R.id.content_6_1);
		content_7_1 = (TextView)findViewById(R.id.content_7_1);
		content_8_1 = (TextView)findViewById(R.id.content_8_1);
		content_9_1 = (TextView)findViewById(R.id.content_9_1);
		content_10_1 = (TextView)findViewById(R.id.content_10_1);
		
		btn_exit = (ImageButton)findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		disinfectionAdapter = new DisinfectionCommAdapter();
		
		listView = (ListView)findViewById(R.id.disinfection_detail_list);
		
		myapp.showDialogNo(context);
		temp = "처음검색";
		threadStart();
	}
	
	public void threadStart(){
		if("처음검색".equals(temp)){
    		disfectionThread = new DisinfectionCommandThread(context, this
    				, myapp.getLoginItem().getOffCd(), serchRecNo, AppStatus.getmUserId());
    		disfectionThread.start();
    	}
	}
	
	private void layoutSetting(){
		content_1_1.setText(disfectionItem.getFullCmmdNo());
		content_1_2.setText(disfectionItem.getFirstCmmdDe());
		content_2_1.setText(disfectionItem.getUserNm());
		content_2_2.setText(disfectionItem.getStatus());
		content_3_1.setText(disfectionItem.getAntMetNm());
		content_4_1.setText(disfectionItem.getActDefr());
		content_4_2.setText(disfectionItem.getActDeto());
		content_5_1.setText(disfectionItem.getMedNm());
		content_6_1.setText(disfectionItem.getMedEtc());
		content_7_1.setText(disfectionItem.getAntRes());
		content_8_1.setText(disfectionItem.getDbyhsScncenm());
		content_9_1.setText(disfectionItem.getGooArea());
		content_10_1.setText(disfectionItem.getWorArea());
		
		disfectionListItem = disfectionItem.getItems();
		
		View header = getLayoutInflater().inflate(R.layout.list_header, null, false);
		
		headerTotTxt = (TextView)header.findViewById(R.id.header_tot);
		upBtn = (ImageButton)header.findViewById(R.id.header_up_btn);
		downBtn = (ImageButton)header.findViewById(R.id.header_down_btn);

		headerTotTxt.setText("총 품목:"+disfectionItem.getItemsResult()+"건");
		listView.addHeaderView(header);	
		listView.setAdapter(disinfectionAdapter);
		
		upBtn.setOnClickListener(this);
		downBtn.setOnClickListener(this);
	}
	
	@Override
	public void OnDisinfectionCommandCompleted(boolean isNetworkConntected,
			DisinfectionCommandItem disfectionItem, String message) {
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(disfectionItem != null) {
			this.disfectionItem = disfectionItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
		
	}

	@Override
	public void OnDisinfectionCommandError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
		
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				layoutSetting();
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				myapp.utilm.ShowDialog(DisinfectionCommActivity.this, "실패", errMsg, 20);
				
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(DisinfectionCommActivity.this, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
	class DisinfectionCommAdapter extends BaseAdapter {
		TextView comm_rec_no, comm_ins_qty;
		TextView comm_prod_cd, comm_prod_name, comm_fmt_cnt;
		
		@Override
		public int getCount() {
			return disfectionListItem.size();
		}

		@Override
		public Object getItem(int position) {
			return disfectionListItem.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_comm_item, parent, false);
    		}
			
			comm_rec_no = (TextView)convertView.findViewById(R.id.comm_rec_no);
			comm_ins_qty = (TextView)convertView.findViewById(R.id.comm_ins_qty);
			comm_prod_cd = (TextView)convertView.findViewById(R.id.comm_prod_cd);
			comm_prod_name = (TextView)convertView.findViewById(R.id.comm_prod_name);
			comm_fmt_cnt = (TextView)convertView.findViewById(R.id.comm_fmt_cnt);

			comm_rec_no.setText(disfectionListItem.get(position).getFullRecNo());
			comm_ins_qty.setText(disfectionListItem.get(position).getInsQty() + disfectionListItem.get(position).getQunNm());
			comm_prod_cd.setText(disfectionListItem.get(position).getPrdlstCd());
			comm_prod_name.setText(disfectionListItem.get(position).getPrdlstNm());
			comm_fmt_cnt.setText(disfectionListItem.get(position).getFmtAntCmmdQty() + disfectionListItem.get(position).getQunNm());
			
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			myapp.utilm.showToast(context, position+"번째 클릭");
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.header_up_btn:
			RelativeLayout.LayoutParams listParams = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 450));
			listParams.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams);
			break;
		case R.id.header_down_btn:
			RelativeLayout.LayoutParams listParams1 = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 100));
			listParams1.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams1);
			break;
		}
	}	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}
	
	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
	
}
